<!--
 * @Author: your name
 * @Date: 2022-01-20 21:38:03
 * @LastEditTime: 2022-02-17 09:31:12
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue-element-admin\src\components\TableGeneral\index.vue
-->
<template>
  <div id="app">
    <div class="tools" v-if="!gridData">
      <div>
        <el-form
          ref="form"
          :form="searchFormObj"
          :label-width="labelWidth"
          v-loading="loading || inLoading"
          class="tools-left"
          v-show="showSearchArray.length > 0"
        >
          <el-form-item
            :label="tableColumn[item].title"
            v-for="(item, index) in showSearchArray"
            label-position="right"
            :key="index"
            style="margin-left: 10px"
          >
            <template
              v-if="
                !tableColumn[item].hasOwnProperty('dataType') ||
                tableColumn[item].dataType == 'text'
              "
            >
              <el-input
                placeholder="请输入内容"
                v-model="searchFormObj[item]['value']"
                :style="{ width: inputWidth }"
                clearable
              ></el-input>
            </template>
            <template v-else-if="tableColumn[item].dataType == 'select'">
              <el-select
                placeholder="请选择"
                v-model="searchFormObj[item]['value']"
                :style="{ width: inputWidth }"
                clearable
              >
                <el-option
                  :label="items.title"
                  :value="items.value"
                  v-for="(items, indexs) in tableColumn[item].selectOptions"
                  :key="indexs"
                ></el-option>
              </el-select>
            </template>


          <template v-else-if="tableColumn[item].dataType == 'selectNum'">
              <el-select
                placeholder="请选择"
                v-model="searchFormObj[item]['value']"
                :style="{ width: inputWidth }"
                clearable
                :ref="'selectNum_'+index"
                @change="selectChange($event,'selectNum_'+index,tableColumn[item])"
              >
                <el-option
                :label="' '"
                :value="index.toString()"
                v-for="index of tableColumn[item].selectNum"
                :key="index"
                ><i
                  :style="{color:tableColumn[item].color ? tableColumn[item].color:'#ece91f'}"
                  :class="tableColumn[item].icon"
                  v-for="indexs of index"
                  :key="indexs"
                ></i
              ></el-option>


              </el-select>
            </template>



          </el-form-item>

          <el-form-item>
            <el-button type="info" @click="onSubmit" icon="el-icon-search"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <div class="tools-right" v-loading="loading || inLoading">
        <el-dropdown trigger="click" size="medium" :hide-on-click="false">
          <el-tooltip
            class="item"
            effect="dark"
            content="列配置"
            placement="top"
          >
            <span
              class="el-dropdown-link"
              @mouseover="moveIn = true"
              @mouseout="moveIn = false"
            >
              <i
                class="el-icon-setting"
                :style="{
                  'font-size': '22px',
                  color: moveIn ? '#409EFF' : 'black',
                }"
              ></i>
            </span>
          </el-tooltip>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(item, index) in tableColumn"
              :key="index"
              class="dropdown-item"
              ><el-checkbox
                :checked="item.column_show"
                @change="columnChange(index, item)"
                >{{ item.title }}</el-checkbox
              >
              <div>
                <i
                  :class="[
                    'el-icon-download',
                    'icon',
                    'trans-left',
                    item.position == 'left' ? 'selColor' : 'noColor',
                  ]"
                  title="左浮动"
                  @click="changePosition(index, 'left')"
                ></i>

                <i
                  :class="[
                    'el-icon-download',
                    'icon',
                    'trans-right',
                    item.position == 'right' ? 'selColor' : 'noColor',
                  ]"
                  title="右浮动"
                  @click="changePosition(index, 'right')"
                ></i>

                <i
                  :class="[
                    'el-icon-search',
                    'icon',
                    showSearchArray.indexOf(index) != -1
                      ? 'selColor'
                      : 'noColor',
                  ]"
                  :style="{ visibility: !item.noSearch ? 'visible' : 'hidden' }"
                  title="搜索"
                  @click="searchShow(index)"
                ></i>
              </div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown trigger="click" size="medium" :hide-on-click="false">
          <el-tooltip
            class="item"
            effect="dark"
            content="刷新"
            placement="top"
            v-show="showRefresh"
            ><span
              class="el-dropdown-link"
              @mouseover="moveInRe = true"
              @mouseout="moveInRe = false"
              @click="refresh"
              style="margin-left: 10px"
            >
              <i
                class="el-icon-refresh-right"
                :style="{
                  'font-size': '22px',
                  color: moveInRe ? '#409EFF' : 'black',
                }"
              ></i>
            </span>
          </el-tooltip>
          <el-dropdown-menu> </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <el-empty description="暂无数据" v-show="tableArray.length == 0"></el-empty>

    <div v-show="tableArray.length > 0" ref="tableContainerDiv">
      <template v-if="multiSelect">
        <el-collapse accordion style="margin-bottom: 100px">
          <el-collapse-item>
            <template slot="title">
              已选中
              <el-badge :value="allSelList.length" class="item"> </el-badge>
            </template>

            <el-empty
              description="暂无数据"
              v-show="allSelList.length == 0"
            ></el-empty>
            <el-table
              style="width: 100%"
              type="expand"
              
              v-bind="{ ...tableConfig, data: allSelList }"
              v-show="allSelList.length > 0"
            >
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form
                    label-position="left"
                    inline
                    class="demo-table-expand"
                    :style="{'width':tableWidth+'px'}"
                  >
                    <el-form-item
                      :label="`${item.title}:`"
                      v-for="(item, index) in tableColumn"
                      :key="index"
                      class="form-item-part"
                    >
                      <template v-if="item.hasOwnProperty('scopedSlots')">
                        <slot
                          :name="item.scopedSlots"
                          :scopeRow="props.row"
                        ></slot>
                      </template>
                      <template v-else>
                        {{ props.row[item.dataIndex] }}
                      </template>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column width="40" v-if="multiSelect">
                <template slot-scope="{ $index }">
                  <div
                    class="minus-button"
                    title="取消选中"
                    @click="clearSel($index)"
                  >
                    <i class="el-icon-minus"></i>
                  </div>
                  <!-- {{$index}} -->
                </template>
              </el-table-column>
              <el-table-column
                :label="item.title"
                :prop="item.dataIndex"
                :key="index"
                :width="item.width"
                v-for="(item, index) in tableArray"
                :fixed="item.position"
              >
                <template slot-scope="scope">
                  <template v-if="item.hasOwnProperty('scopedSlots')">
                    <slot :name="item.scopedSlots" :scopeRow="scope.row"></slot>
                  </template>
                  <template v-else>
                    <!--无插槽  -->
                    <span :title="scope.row[item.dataIndex]">
                      {{ scope.row[item.dataIndex] }}
                    </span>
                  </template>
                  <!-- </template> -->
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </template>

      <el-table
        style="width: 100%"
        v-loading="loading || inLoading"
        type="expand"
        v-bind="{ ...tableConfig, data: tableData }"
        @expand-change="expandChange"
        @selection-change="handleSelectionChange"

        ref="tableScroll"
      >
       <el-table-column
      type="selection"
      width="55" v-if="selection" align="center" :selectable="selectable">
    </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline :style="{'width':tableWidth+'px'}" class="demo-table-expand">
              <el-form-item
                :label="`${item.title}:`"
                v-for="(item, index) in tableColumn"
                :key="index"
                class="form-item-part"
              >
                <template v-if="item.hasOwnProperty('scopedSlots')">
                  <slot :name="item.scopedSlots" :scopeRow="props.row"></slot>
                </template>
                <template v-else>
                  {{ props.row[item.dataIndex] }}
                </template>
              </el-form-item>

              <el-form-item
                :label="`${item}:`"
                v-for="(item, index) in slotArray"
                :key="'slot' + index"
                class="form-item-part"
              >
                <slot :name="item" :scopeRow="props.row"></slot>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        
        <el-table-column width="55" label="选择" v-if="multiSelect">
          <template slot-scope="scope">
            <el-checkbox
              :label="scope.row.id"
              v-model="checkList"
              @change="checkListChange"
            >
              <br />
            </el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
          :label="item.title"
          :prop="item.dataIndex"
          :key="index"
          :width="item.width"
          v-for="(item, index) in tableArray"
          :fixed="item.position"
          :show-overflow-tooltip="true"
          :resizable="false"
        >
          <template slot-scope="scope">
            <!-- <div class="table-part"> -->
            <template v-if="item.hasOwnProperty('scopedSlots')">
              <div class="table-part">
              <slot :name="item.scopedSlots" :scopeRow="scope.row"></slot>
              </div>
            </template>
            <template v-else>
              <!--无插槽  -->
              <span>
                {{ scope.row[item.dataIndex] }}
              </span>
            </template>
            <!-- </div> -->
          </template>
        </el-table-column>

        <el-table-column></el-table-column>
      </el-table>
    </div>
  </div>
</template>
        
<script>
export default {
  name: "app",
  components: {},
  props: {
    tableData: {
      type: Array,
      default: [],
    },
    tableColumn: {
      type: Array,
      default: [],
    },
    loading: {
      type: Boolean,
      default: false,
    },
    tableConfig: {
      type: Object,
      default: () => {
        return {};
      },
    },
    labelWidth: {
      type: String,
      default: "100px",
    },
    inputWidth: {
      type: String,
      default: "200px",
    },
    showRefresh: {
      type: Boolean,
      default: true,
    },
    multiSelect: {
      type: Boolean,
      default: false,
    },
    allSelList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    gridData: {
      type: Boolean,
      default: false,
    },
    checkListDefault: {
      type: Array,
      default: () => {
        return [];
      },
    },
    slotArray: {
      type: Array,
      default: () => {
        return [];
      },
    },
    selection:{   //表格多选
      type: Boolean,
      default:false
    },
    selectionFunc:{
       type: Function,
        default:()=>{
          return true
        }
    }
  },
  data() {
    return {
      moveIn: false,
      moveInRe: false,
      drawerVisible: true,
      checkList: [], //多选
      oldCheckList: [], //旧多选
      showSearchArray: [],
      searchFormObj: {},
      manyFieldObj: {},
      inLoading: false,
      tableShowMore: false,
      multipleSelection:[],
      tableWidth:800
    };
  },
  created() {
    for (let i = 0; i < this.tableColumn.length; i++) {
      this.tableColumn[i].column_show = true;
      this.tableColumn[i].position = this.tableColumn[i].hasOwnProperty(
        "position"
      )
        ? this.tableColumn[i].position
        : null;
      let field = this.tableColumn[i].hasOwnProperty("returnField")
        ? this.tableColumn[i].returnField
        : this.tableColumn[i].dataIndex;
      this.$set(this.searchFormObj, i, { value: "", filed: field });
      if (this.tableColumn[i].hasOwnProperty("manyField")) {
        //多个字段搜索
        this.manyFieldObj[field] = this.tableColumn[i].manyField;
      }
    }

    if (this.allSelList.length > 0) {
      let array = this.allSelList.map((item) => item.id);
      this.checkList = array;
      this.oldCheckList = array;
    } else {
      this.checkList = [];
      this.oldCheckList = [];
    }
  }, //生命周期 - 创建完成（可以访问当前this实例）
  mounted() {
    let offsetWidth = this.$refs.tableScroll.$el.offsetWidth 
    console.log(offsetWidth)
    if(offsetWidth > 250){
       this.tableWidth =offsetWidth-250
    }
    console.log( this.tableWidth)
    // console.log(this.tableWidth )
    // ref="tableScroll"
  }, //生命周期 - 挂载完成（可以访问DOM元素）
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  watch: {},
  computed: {
    tableArray: function () {
      return this.tableColumn.filter(function (tableColumn) {
        return tableColumn.column_show; //返回column_show=true的项，添加到tableArray数组
      });
    },
  },
  methods: {
    selectChange(e,refName,row){
       this.$refs[refName][0].$el.children[0].setAttribute(
            "style",
            "position: relative"
          );
          let str = "";
          for (let i = 0; i < e; i++) {
            str += `<i
                     style="color: ${row.color}"
                     class="${row.icon}" ></i>`;
          }
          let div = document.createElement("div"); //创建新标签
          div.innerHTML = str; 
          div.style = "color:red;position: absolute;left:15px;top:0";
          let Vnode = this.$refs[refName][0].$el.children[0].children[2];
          if (Vnode) {
            this.$refs[refName][0].$el.children[0].removeChild(Vnode);
          }
          this.$refs[refName][0].$el.children[0].appendChild(div);
    },
    columnChange(index, item) {
      item.column_show = item.column_show ? false : true;
      this.$set(this.tableColumn, index, item);
      // this.checkWidth()  // 检查宽度变化
    },
    selectable(row, index){
      //  return false;
        return this.selectionFunc(row, index)
    },
    onSubmit() {
      let keyWord = {};
      for (let key in this.showSearchArray) {
        let keys = this.searchFormObj[this.showSearchArray[key]].filed;
        let value = this.searchFormObj[this.showSearchArray[key]].value;
        if (this.manyFieldObj.hasOwnProperty(keys)) {
          if (!keyWord.hasOwnProperty("manyField")) {
            keyWord.manyField = [];
          }
          let obj = {};
          for (let i = 0; i < this.manyFieldObj[keys].length; i++) {
            let fiekdKey = this.manyFieldObj[keys][i];
            obj[fiekdKey] = value;
          }
          keyWord.manyField.push(obj);
        } else {
          keyWord[keys] = value;
        }
      }
      this.$emit("search", keyWord);
    },
    searchShow(index) {
      let indexOf = this.showSearchArray.indexOf(index);

      if (indexOf != -1) {
        this.showSearchArray.splice(indexOf, 1);
        this.searchFormObj[indexOf].value = "";
        this.onSubmit();
      } else {
        this.showSearchArray.push(index);
      }
    },
    refresh() {
      this.$emit("refresh");
    },
    clearSel(index) {
      this.inLoading = true;
      let allSelListId = this.allSelList[index].id;
      let checkList = this.checkList;
      let allSelListIndexOf = checkList.indexOf(allSelListId);
      if (allSelListIndexOf != -1) {
        checkList.splice(allSelListIndexOf, 1);
        this.oldCheckList = checkList;
        this.$set(this, "checkList", checkList);
      }
      this.allSelList.splice(index, 1);
      this.$nextTick(() => {
        this.inLoading = false;
      });
    },
    changePosition(index, position) {
      let tableColumn = this.tableColumn[index];
      tableColumn.position = tableColumn.position == position ? null : position;
      this.$set(this.tableColumn, index, tableColumn);
    },
    checkListChange(add) {
      this.inLoading = true;

      let checkList = JSON.parse(JSON.stringify(this.checkList));
      if (add) {
        var lessArray = this.oldCheckList;
        var moreArray = checkList;
      } else {
        var moreArray = this.oldCheckList;
        var lessArray = checkList;
      }
      for (let i = 0; i < moreArray.length; i++) {
        let lessArrayIndexOf = lessArray.indexOf(moreArray[i]);
        if (lessArrayIndexOf == -1) {
          //找到少的没有 就是 添加或者删除
          add
            ? this.allSelList.push(
                this.tableData.find((value) => value.id == moreArray[i])
              )
            : this.allSelList.splice(
                this.allSelList.findIndex((value) => value.id == moreArray[i]),
                1
              );
        }
      }
      this.oldCheckList = checkList;
      this.inLoading = false;
    },
    expandChange(row, expandedRows) {
      this.$emit("expandChange", row, expandedRows);
    },
    handleSelectionChange(val){
      // console.log(val)
       this.multipleSelection = val;
    }
  },
};
</script>
<style lang="less" scoped>
.el-dropdown-link {
  cursor: pointer;
  // color: black;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.demonstration {
  display: block;
  color: #8492a6;
  font-size: 14px;
  margin-bottom: 20px;
}
.tools {
  width: 95%;
  display: flex;
  margin-top: 30px;
  //   margin-left: 30px;
  margin-right: 20px;
  justify-content: space-between;
  margin-bottom: 10px;
}

.el-dropdown-menu__item {
  cursor: auto;
}
.el-dropdown-menu__item:not(.is-disabled):hover,
.el-dropdown-menu__item:focus {
  background-color: white;
  color: #606266;
}

.dropdown-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.icon {
  margin-left: 20px;
  cursor: pointer;
}
.selColor {
  color: #409eff;
}
.noColor {
  color: black;
}
.tools-left {
  display: flex;
  flex-wrap: wrap;
  flex: 1;
}
.tools-right {
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
  width: 100px;
  padding-bottom: 15px;
}
.trans-left {
  transform: rotate(90deg);
}
.trans-right {
  transform: rotate(-90deg);
}
.item {
  margin-top: 10px;
  // margin-right: 40px;
  margin-left: 10px;
}
.minus-button {
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: red;
  border-radius: 100%;
  font-size: 5px;
  color: white;
}

.demo-table-expand {
  font-size: 0;
  display: flex;
  flex-direction: column;
  // flex: 1;
  // border: 1px solid red;
  width: 400px;
  word-break:break-all;
  // padding-left: 65px;
  // flex-wrap: wrap;

  // padding-right: 100px;
}
.form-item-part{
  // border: 1px solid red;
  // width: 1400px;

  // flex: 1;
  
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  flex: 1;
  padding-left: 45px;
}
.table-part {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.demo-table-expand {
  font-size: 0;
  padding-left: 20px;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  // width: 50%;
}
</style>
